package com.hello.syn;

/**
 * 死锁：过多的同步造成相互不释放资源，从而相互等待，一般发生在同步中持有多个对象锁。
 */
public class DeadLock {
    public static void main(String[] args) {
        Markup g1 = new Markup(0, "一号");
        Markup g2 = new Markup(1, "二号");
        g1.start();
        g2.start();
    }

}

// 口红
class Lipstick{

}

// 镜子
class Mirror{

}

// 化妆
class Markup extends Thread{
    static Lipstick lipstick = new Lipstick();
    static Mirror mirror = new Mirror();
    int choice;
    String girl;

    public Markup(int choice, String girl){
        this.choice = choice;
        this.girl = girl;
    }

    @Override
    public void run(){
        markup();
    }

    private void markup(){
        if (choice == 0) {
            synchronized (lipstick){
                System.out.println(this.girl+"获得口红");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // 死锁
//                synchronized (mirror){
//                    System.out.println(this.girl+"获得镜子");
//                }
            }
            // 没有死锁
            synchronized (mirror){
                System.out.println(this.girl+"获得镜子");
            }
        } else {
            synchronized (mirror){
                System.out.println(this.girl+"获得镜子");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // 死锁
//                synchronized (lipstick){
//                    System.out.println(this.girl+"获得口红");
//                }
            }
            // 没有死锁
            synchronized (lipstick){
                System.out.println(this.girl+"获得口红");
            }
        }
    }

}